package org.lucava.boatskeeper.server;

import java.util.ArrayList;
import java.util.List;

import org.lucava.boatskeeper.client.BoatsKeeperService;
import org.lucava.boatskeeper.shared.Boat;
import org.lucava.boatskeeper.shared.FieldVerifier;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class BoatsKeeperServiceImpl extends RemoteServiceServlet implements
		BoatsKeeperService {

	private final List<Boat> mBoats = new ArrayList<Boat>();

	public String addBoat(Boat aBoat) throws IllegalArgumentException {
		// Verify that the input is valid.
		if (!FieldVerifier.isValidName(aBoat.getName())) {
			// If the input is not valid, throw an IllegalArgumentException back
			// to the client.
			throw new IllegalArgumentException(
					"Name must be at least 4 characters long");
		}

		aBoat.setName(this.escapeHtml(aBoat.getName()));
		aBoat.setType(this.escapeHtml(aBoat.getType()));
		aBoat.setDescription(this.escapeHtml(aBoat.getDescription()));

		this.getBoats().add(aBoat);

		return "Bateau ajouté avec succès!";
	}

	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 * 
	 * @param html
	 *            the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}

	public List<Boat> getBoats() {
		return mBoats;
	}
}
